import store from "../../config/store";

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return timeStr;
}

export function formatTime(time, option) {
  time = +time * 1000;
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {Sting} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (let i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) {
      s++;
    } else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  );
}

export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

export function objectMerge(target, source) {
  /* Merges two  objects,
       giving the last one precedence */

  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

export const pickerOptions = [
  {
    text: "今天",
    onClick(picker) {
      const end = new Date();
      const start = new Date(new Date().toDateString());
      end.setTime(start.getTime());
      picker.$emit("pick", [start, end]);
    }
  },
  {
    text: "最近一周",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7);
      picker.$emit("pick", [start, end]);
    }
  },
  {
    text: "最近一个月",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      picker.$emit("pick", [start, end]);
    }
  },
  {
    text: "最近三个月",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      picker.$emit("pick", [start, end]);
    }
  }
];

export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

export function throttle(fn, wait, immediate) {
  let timer;
  let context, args;

  let run = () => {
    timer = setTimeout(() => {
      if (!immediate) {
        fn.apply(context, args);
      }
      clearTimeout(timer);
      timer = null;
    }, wait);
  };

  return function () {
    context = this;
    args = arguments;
    if (!timer) {
      if (immediate) {
        fn.apply(context, args);
      }
      run();
    }
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "shallowClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

export function trans(obj) {
  const _routeObj = {};
  _routeObj.name = obj.name;
  _routeObj.path = obj.url;
  _routeObj.redirect = obj.redirect || "";
  _routeObj.meta = obj.meta || {};
  _routeObj.meta.title = obj.name;
  _routeObj.meta.isNotShow = obj.isShowSideBar;
  return _routeObj;
}

export function routerObj2MenuObj(item) {
  const menuObj = {};
  menuObj.subMenuTitle = item.name;
  if (item.subMenu.length) {
    const subMenuArr = [];
    item.subMenu.forEach(menuItem => {
      subMenuArr.push(trans(menuItem));
    });
    menuObj.subMenu = subMenuArr;
  }
  return menuObj;
}

export function getCurMenuObj(arr, menuCode) {
  // let obj = {}
  // let menu = []

  if (arr.length !== 0) {
    let traverse = arr => {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].subMenu && arr[i].subMenu.length !== 0) {
          // 获取当前菜单
          if (arr[i].menuCode === menuCode) {
            // 获取当前菜单的父菜单
            // obj = arr[i]
            // debugger
            const strArr = arr[i].id.split("-");
            const curMenuId = strArr[0] + "-" + strArr[1];

            const curMenu = store.state.app.menu.forEach(item => {
              return item.id === curMenuId;
            });
            store.dispatch("setCurrentMenuArr", curMenu);
          }
          traverse(arr[i].subMenu);
        } else {
          if (arr[i].menuCode === menuCode) {
            // 获取当前菜单的父菜单
            // alert(3)
            // obj = arr[i]
            const strArr = arr[i].id.split("-");
            const curMenuId = strArr[0] + "-" + strArr[1];
            const curMenu = store.state.app.menu.filter(item => {
              return item.id === curMenuId;
            });
            const menuArr = [];
            curMenu[0].subMenu.forEach(item => {
              const menuObj = routerObj2MenuObj(item);
              menuArr.push(menuObj);
            });
            store.dispatch("setCurrentMenuArr", menuArr);
          }
        }
      }
    };
    traverse(arr);
  }

  // return menu
}

export function findIndex(list, prop, id) {
  let lastIndex;
  list.forEach((item, index) => {
    if (item[prop] === id) {
      lastIndex = index;
    }
  });
  return lastIndex;
}

// 数字转为千分位
export function numberFilter(oldNum, isFixed) {
  if (oldNum === "") return {};
  let newNum = oldNum.toLocaleString("en-US");
  const numArr = newNum.split(".");
  if (!isFixed) {
    if (!numArr[1]) {
      newNum = newNum + ".00";
    } else if (numArr[1].length === 1) {
      newNum = newNum + "0";
    } else if (numArr[1].length >= 2) {
      newNum = numArr[0] + "." + numArr[1].substr(0, 2);
    }
  }
  return { oldNum, newNum };
}

//金额显示两位小数
export function moneyFilter(oldNum, isFixed) {
  if (oldNum === "" || oldNum == null) return {};
  let newNum = oldNum;
  const numArr = newNum.split(".");
  if (!isFixed) {
    if (!numArr[1]) {
      newNum = newNum + ".00";
    } else if (numArr[1].length === 1) {
      newNum = newNum + "0";
    } else if (numArr[1].length >= 2) {
      newNum = numArr[0] + "." + numArr[1].substr(0, 2);
    }
  }
  return { oldNum, newNum };
}

//数字显示指定位小数，默认两位，不足位数的不补0，zdz加
export function floatNum(oldNum, isFixed = 2) {
  if (oldNum === "" || oldNum == null) return "";
  let newNum = oldNum + "";
  if (newNum.indexOf(".") == -1) {
    return newNum;
  } else {
    const numArr = newNum.split(".");
    if (numArr[1].length >= isFixed) {
      newNum = numArr[0] + "." + numArr[1].substr(0, isFixed);
    } else {
      newNum = numArr[0] + "." + numArr[1].substr(0, numArr[1].length);
    }
    return newNum;
  }
}

// 处理金额小数点后保留几位
export function formatNumber(value, num) {
  if (value === "" || value === null) return "";
  let a, b, c, i;
  a = value.toString();
  b = a.indexOf(".");
  c = a.length;
  if (num === 0) {
    if (b !== -1) {
      a = a.substring(0, b);
    }
  } else {
    //如果没有小数点
    if (b === -1) {
      a = a + ".";
      for (i = 1; i <= num; i++) {
        a = a + "0";
      }
    } else {
      //有小数点，超出位数自动截取，否则补0
      a = a.substring(0, b + num + 1);
      for (i = c; i <= b + num; i++) {
        a = a + "0";
      }
    }
  }
  return a;
}

// 判断是否为空串,导出excel时空串不格式化
export function isSpace(str) {
  if (str.length > 0) {
    return Number(str.replace(/,/g, ""));
  } else {
    return str;
  }
}

// 清楚千分位
export function clearComma(s) {
  return Number((s + "").replace(/[,]/g, ""));
}

// 去掉时分秒
export function newDate(date) {
  let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date);
  return newDate;
}

// 多行文本框空格回车转换
export function textAreaRule(text) {
  let textString;
  textString = text.replace(/\n/g, "<br>").replace(/\s/g, "&nbsp;");
  return textString;
}

// 转换文本域空格和换行
export function changetextArea(text) {
  let textString;
  textString = text.replace(/<br\s*\/?>/gi, "\n").replace(/&nbsp;/gi, " ");
  return textString;
}

export function salary(money) {
  let regexp = /(^[1-9]([0-9]+)?(\.[0-9]{2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (money) {
    if (money.length > 8) {
      if (money.toString().indexOf(".") == -1) {
        return false;
      }
    }
    if (!regexp.test(money)) {
      return false;
    }
  }
}

// note 判断当前浏览器的名称和版本号
export function checkBrowser() {
  const ua = navigator.userAgent.toLocaleLowerCase();
  const browser = {
    name: null,
    version: null
  };
  if (ua.match(/chrome/) != null) {
    // 判断是否是360极速模式
    let _mime = (option, value) => {
      let mimeTypes = navigator.mimeTypes;
      for (let mt in mimeTypes) {
        if (mimeTypes[mt][option] === value) {
          return true;
        }
      }
      return false;
    };
    let is360 = _mime("type", "application/vnd.chromium.remoting-viewer");

    if (is360) {
      browser.is360 = true;
      browser.name = "360";
    } else {
      browser.isChrome = true;
      browser.name = "Chrome";
    }
  } else if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
    browser.isIE = true;
    browser.name = "IE";
    browser.version =
      ua.match(/msie ([\d.]+)/) != null
        ? ua.match(/msie ([\d.]+)/)[1]
        : ua.match(/rv:([\d.]+)/)[1];
  } else if (ua.match(/edge/) != null) {
    browser.isEdge = true;
    browser.name = "Edge";
  } else if (ua.match(/firefox/) != null) {
    // 火狐
    browser.isFirefox = true;
    browser.name = "FireFox";
  } else if (ua.match(/safari/) != null) {
    // 苹果
    browser.isSafari = true;
    browser.name = "Safari";
  } else if (ua.match(/ubrowser/) != null) {
    // UC
    browser.isUC = true;
    browser.name = "UC";
  } else if (ua.match(/opera|opr/) != null) {
    // 欧朋
    browser.isOpera = true;
    browser.name = "Opera";
  } else if (ua.match(/bidubrowser/) != null) {
    // 百度
    browser.isBaidu = true;
    browser.name = "Baidu";
  } else if (ua.match(/metasr/) != null) {
    // 搜狗
    browser.isSogou = true;
    browser.name = "Sogou";
  } else if (ua.match(/qqbrowse|tencenttraveler/)) {
    browser.isQQ = true;
    browser.name = "QQ";
  } else if (ua.match(/maxthon/) != null) {
    // 遨游
    browser.isMaxthon = true;
    browser.name = "Maxthon";
  }
  return browser;
}

// 是否是推荐浏览器
export function isSupportExplore() {
  const browser = checkBrowser();
  // edeg 谷歌 ie11以上
  return (
    browser.isEdge ||
    browser.isChrome ||
    browser.is360 ||
    browser.isFirefox ||
    browser.isSafari ||
    (browser.isIE && browser.version >= 10)
  );
}

// 判断ie版本支持情况
export function isSupportIEVersion() {
  const browser = checkBrowser();
  if (!browser.isIE) {
    // 非IE
    return true;
  } else if (browser.isIE && browser.version >= 11) {
    // 是IE，且版本在11以上
    return true;
  } else {
    // IE版本在11以下
    return false;
  }
}

export function swapItems(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
}

// 上移一位
export function upRecord(arr, $index) {
  if ($index === arr.length - 1) {
    return;
  }
  swapItems(arr, $index + 1, $index);
}

// 下移一位
export function downRecord(arr, $index) {
  if ($index === 0) {
    return;
  }
  swapItems(arr, $index, $index - 1);
}

export function dateFormat(fmt, date) {
  console.log(fmt, date);
  let ret;
  let opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
}

// 时间格式化
export function dateFormat1(time) {
  const date = new Date(time);
  const Y = date.getFullYear() + "-";
  const M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  const D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  return Y + M + D;
}

export function proxyDateFormat(time) {
  return time.substring(0, time.indexOf(" "));
}

// 设置缓存项
export function setSessionItem(moduleName, key, value) {
  let val = getSessionItem(moduleName) || {};
  val[key] = value;
  localStorage.setItem(moduleName, JSON.stringify(val));
}

// 读取缓存项
export function getSessionItem(moduleName, key) {
  if (key) {
    return (
      localStorage.getItem(moduleName) &&
      JSON.parse(localStorage.getItem(moduleName))[key]
    );
  } else {
    return JSON.parse(localStorage.getItem(moduleName));
  }
}

// 删除缓存项
export function removeSessionItem(moduleName, key) {
  if (key) {
    let val = getSessionItem(moduleName);
    delete val[key];
    localStorage.setItem(moduleName, JSON.stringify(val));
  } else {
    localStorage.removeItem(moduleName);
  }
}

// 获取agentId
export function getArgs(argName) {
  //地址栏携带属性
  if (!argName) {
    return false;
  }
  let query = location.search.substring(1);
  let pairs = query.split("&");
  for (let i = 0; i < pairs.length; i++) {
    let pos = pairs[i].indexOf("=");
    if (pos == -1) continue;
    let argname = pairs[i].substring(0, pos),
      value = pairs[i].substring(pos + 1);
    value = decodeURIComponent(value);
    if (argName == argname) {
      return value;
    }
  }
}

// 拼接缓存所需要的key
export function ishasAgentId(path, key) {
  if (key.includes("?")) {
    if (key.includes(path)) {
      let str = key.split("?")[1];
      return `${path}?${str}`;
    }
  } else {
    return path;
  }
}

export function addUrlPerFix(url) {
  const o = window.location;
  if (o.hostname === "localhost") {
    switch (o.port) {
      case "3000": {
        return o.protocol + "//dev01-" + url;
      }
      case "3001": {
        return o.protocol + "//test01-" + url;
      }
      case "3002": {
        return o.protocol + "//uat01-" + url;
      }
    }
  } else {
    let arr = o.hostname.split("-");
    let perfix = arr.length === 1 ? "" : arr[0] + "-";
    return o.protocol + "//" + perfix + url;
  }
}


//为复制删除加标志
export function generateUUID() {
  let d = new Date().getTime();
  let uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (
    c
  ) {
    let r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
  return uuid;
  // URL.createObjectURL(new Blob()).substr(-36)
}

// 时间处理
export function setDate(item) {
  // 循环数组
  if (Array.isArray(item)) {
    item.map(Item => {
      this.setDate(Item);
    });
  } else {
    // 循环对象
    for (let key in item) {
      if (item[key]) {
        if (key.indexOf("Date") != -1 || key.indexOf("Time") != -1) {
          item[key] = item[key].split(" ")[0];
        }
        // 判断类型为 对象类型 循环
        if (item[key] instanceof Object) {
          this.setDate(item[key]);
        }
      }
    }
  }
}

/*
 * 导入组件
 * */
export function importComponent(r) {
  let __modules = {};
  r.keys().forEach(key => {
    let m = r(key).default;
    let n = m.name;
    __modules[n] = m;
  });
  return __modules;
}

// 数组对象去重
export function uniqueByJson(arr, value) {
  // const obj = {}
  // return arr.reduce((cur, next) => {
  //   obj[arr[value]] ? '' : obj[arr[value]] = true && cur.push(next)
  //   return cur
  // }, [])
  return arr.reduce((pre, cur) => {
    if (pre.find(c => c[value] === cur[value])) {
      return pre;
    } else {
      return [...pre, cur];
    }
  }, []);
}

export function numberToChinese(num) {
  let AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
  let BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
  let a = ("" + num).replace(/(^0*)/g, "").split("."),
    k = 0,
    re = "";
  for (let i = a[0].length - 1; i >= 0; i--) {
    switch (k) {
      case 0:
        re = BB[7] + re;
        break;
      case 4:
        if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
          .test(a[0]))
          re = BB[4] + re;
        break;
      case 8:
        re = BB[5] + re;
        BB[7] = BB[5];
        k = 0;
        break;
    }
    if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
      re = AA[0] + re;
    if (a[0].charAt(i) != 0)
      re = AA[a[0].charAt(i)] + BB[k % 4] + re;
    k++;
  }

  if (a.length > 1) // 加上小数部分(如果有小数部分)
  {
    re += BB[6];
    for (let i = 0; i < a[1].length; i++)
      re += AA[a[1].charAt(i)];
  }
  if (re == '一十')
    re = "十";
  if (re.match(/^一/) && re.length == 3)
    re = re.replace("一", "");
  return re;
}

export function setToFixed(val, num) {
  let f = parseFloat(val);
  if (isNaN(f)) {
    return false;
  }
  f = Math.round(val * Math.pow(10, num)) / Math.pow(10, num); // n 幂   
  let s = f.toString();
  let rs = s.indexOf('.');
  //判定如果是整数，增加小数点再补0
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + num) {
    s += '0';
  }
  return s;
}
